#include "thread.h"
#include "thread_list.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

/* Thread_yield
 * Donne la main a un autre thread.
 *
 */
int thread_yield(void){
	//fprintf(stderr,"on est dans thread_yield\n");
	//donner la main à un autre thread...
  
	thread_t * old = current_thread;
	thread_t * p = get_thread(list_thread);

	/*
	if(thread_remove!=NULL){
	free(thread_remove);
	thread_remove=NULL;
	}
	if(current_thread->status==0){
	thread_remove=current_thread;
	}
	*/
	
	if(p == NULL)
	{
		fprintf(stderr,"liste thread est vide !\n");
		//current_thread->t=0;//NULL;
		return -1;
	}
	

	//(list_thread->next->next!=NULL)
	//if(list_thread->next!=NULL)
	//	if(list_thread->next->next!=NULL)

	ucontext_t *pil, *pol;
	
	if(old->id != p->id)
	{
		//printf("swapcontext: %p, %p\n",&(old->t), &(p->t));
		current_thread=p;
		//printf("le current_thread devient : %p\n",current_thread);
		pil=&old->t;
		pol=&p->t;

			if(list_thread->next->next==NULL)
			{
			  //printf("il n'y a plus qu'un thread dans la liste on ne fait pas le thread_yield\n");
			  //print_thread_list(list_thread);
			  free(list_thread->next->thread);
			  free(list_thread->next);
			  
			 free(list_thread);
			  list_thread=NULL;
			  main_initialized = 0;
			  //print_thread_list(list_thread);
			}
		swapcontext(pil, pol);
	}

	return 1;
}


